package br.com.informatos.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class NotesDAO {

	private SQLiteDatabase database;
	private String[] columns = {CUstomSQLiteOpenHelper.COLUMN_ID,
			CUstomSQLiteOpenHelper.COLUMN_NOTES };
	private CUstomSQLiteOpenHelper sqliteopenhelper;


	public NotesDAO(Context context) {
		sqliteopenhelper = new CUstomSQLiteOpenHelper(context);
	}


	public void Open() throws SQLException {
		database = sqliteopenhelper.getWritableDatabase();

	}


	public void close() {
		sqliteopenhelper.close();
	}


	public Note create(String note){
		ContentValues values = new ContentValues();
		values.put(CUstomSQLiteOpenHelper.COLUMN_NOTES, note);
		long InsertId = database.insert(CUstomSQLiteOpenHelper.TABLE_NOTES, null, values);
		Cursor cursor = database.query(CUstomSQLiteOpenHelper.TABLE_NOTES,
		    columns, CUstomSQLiteOpenHelper.COLUMN_ID + " = " + InsertId, null, null, null, null);
		cursor.moveToFirst();
		Note newNote = new Note();
		newNote.setId(cursor.getLong(0));
		newNote.setNote(cursor.getString(1));
		cursor.close();
		return newNote;
	}
	
	
	public void delete (Note note){
		long id = note.getId();
		database.delete(CUstomSQLiteOpenHelper.TABLE_NOTES, CUstomSQLiteOpenHelper.COLUMN_ID
				+ " = " + id, null);
	}
	
	
	public List<Note> getAll(){
		List<Note> notes = new  ArrayList<Note>();
		
		Cursor cursor = database.query(CUstomSQLiteOpenHelper.TABLE_NOTES, columns, null, null, null, null, null);
		
		cursor.moveToFirst();
		while (!cursor.isAfterLast()){
			Note note = new Note();
			note.setNote(cursor.getString(1));
			note.setId(cursor.getInt(0));
			notes.add(note);
			cursor.moveToNext();
		}
		
		cursor.close();
		return notes;
	}


}


